package com.cn.jiyun.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cn.jiyun.entity.pojo.Strategy;
import com.cn.jiyun.entity.pojo.User;
import com.cn.jiyun.mapper.UserMapper;
import com.cn.jiyun.service.UserService;
import com.jiyun.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;


    @PostMapping("/login")
    public Result<User> login(@RequestBody User user) {
        // 从请求中获取用户名和密码
        String username = user.getUsername();
        String password = user.getPassword();
        // 从数据库中查询用户
        User users = userService.getUserByUsernameAndPassword(username, password);
        User user1 = userService.cha(users.getUsername());
        if (users!=null) {
            // 用户存在，登录成功
            // 生成 Token
            String token = UUID.randomUUID().toString();
            // 将用户信息存储到 Redis
            redisTemplate.opsForValue().set(token, JSON.toJSONString(users));
            return Result.ok(users);
        } else {
            // 用户不存在或密码错误，登录失败
           throw new RuntimeException("用户名或密码错误");
        }
    }

    @RequestMapping("/findid")
    public User findid(String username) {
        return userService.findid(username);
    }

    @RequestMapping("/update")
    public void update(@RequestBody User user) {
        userService.up(user);
    }


}
